package com.yuanluludev.pgy

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.text.TextUtils
import com.yuanluludev.lib_base.ext.toastFailedMiddle
import com.yuanluludev.lib_base.net.errorMsg
import com.yuanluludev.lib_utils.util.AppUtils
import com.yuanluludev.pgy.PgyConstants.APK_DOWNLOAD_PATH
import io.reactivex.rxjava3.disposables.Disposable
import rxhttp.wrapper.param.RxHttp

/**
 * yuanLuLu
 * 后台下载的服务
 */
class DownloadService : Service() {

    companion object {
        const val DOWNLOAD_URL = "download_url"
    }

    private var notificationListener: NotificationDownloadListener? = null
    private var disposable: Disposable? = null

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        notificationListener = NotificationDownloadListener(this)
        notificationListener?.onStart()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val downloadUrl = intent?.getStringExtra(DOWNLOAD_URL)
        if (TextUtils.isEmpty(downloadUrl)) {
            "暂无下载地址，下载失败".toastFailedMiddle()
            stopSelf()
        } else {
            //去下载
            disposable = RxHttp.get(downloadUrl).asDownload(APK_DOWNLOAD_PATH) {
                notificationListener?.onProgress(it.progress.toFloat())
            }.subscribe({
                notificationListener?.onFinish()
                if (!TextUtils.isEmpty(it)) AppUtils.installApp(it)
                stopSelf()
            }, {
                it.errorMsg.toastFailedMiddle()
                stopSelf()
            })
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        notificationListener?.onFinish()
        disposable?.apply { if (!this.isDisposed) this.dispose() }
        super.onDestroy()
    }

}